const redis = require('redis')
const { My_Redis_CONFIG } = require('../../conf/db')

// 创建客户端
const redisClient = redis.createClient({
  socket: {
    host: My_Redis_CONFIG.host,
    port: My_Redis_CONFIG.port,
  },
})

// 异步连接 Redis 客户端
redisClient.connect().catch(console.error)

// 捕获错误事件
redisClient.on('error', (err) => {
  console.error('Redis Client Error', err)
})

async function set(key, val) {
  if (typeof val === 'object') {
    val = JSON.stringify(val)
  }
  await redisClient.set(key, val)
}

async function get(key) {
  const val = await redisClient.get(key)
  try {
    return JSON.parse(val)
  } catch (ex) {
    return val
  }
}

// 在连接成功后执行函数
redisClient.on('connect', () => {
  console.log('Redis client connected')
})

module.exports = {
  set,
  get,
}
